package com.wang.vedio.utils;

import android.app.AppOpsManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.google.gson.Gson;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;
import com.wang.vedio.R;
import com.wang.vedio.application.APP;
import com.wang.vedio.net.SharedHelper;
import com.wang.vedio.net.entity.LoginBean;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import static com.wang.vedio.net.rxjava.HttpMethods.BASE_WORK_URL;

/**
 * @author ztk
 */
public class NotificationUtil {
    //判断是否需要打开设置界面
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static void OpenNotificationSetting(Context context, OnNextLitener mOnNextLitener) {
        if (!isNotificationEnabled(context)) {
            showSettingDialog(context, mOnNextLitener);
        } else {
            if (mOnNextLitener != null) {
                mOnNextLitener.onNext(1);
            }
        }
    }

    /**
     * 判断该app是否打开了通知
     * 可以通过NotificationManagerCompat 中的 areNotificationsEnabled()来判断是否开启通知权限。NotificationManagerCompat 在 android.support.v4.app包中，是API 22.1.0 中加入的。而 areNotificationsEnabled()则是在 API 24.1.0之后加入的。
     * areNotificationsEnabled 只对 API 19 及以上版本有效，低于API 19 会一直返回true
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
            boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
            return areNotificationsEnabled;
        }

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 打开手机设置页面
     * 假设没有开启通知权限，点击之后就需要跳转到 APP的通知设置界面，对应的Action是：Settings.ACTION_APP_NOTIFICATION_SETTINGS, 这个Action是 API 26 后增加的
     * 如果在部分手机中无法精确的跳转到 APP对应的通知设置界面，那么我们就考虑直接跳转到 APP信息界面，对应的Action是：Settings.ACTION_APPLICATION_DETAILS_SETTINGS
     */
    private static void gotoSet(Context context) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /*=====================添加Listener回调================================*/
    public interface OnNextLitener {
        /**
         * 不需要设置通知的下一步
         */
        void onNext(int type);
    }

    private OnNextLitener mOnNextLitener;

    public void setOnNextLitener(OnNextLitener mOnNextLitener) {
        this.mOnNextLitener = mOnNextLitener;
    }


    public static void showSettingDialog(final Context mContext, OnNextLitener mOnNextLitener) {
        RxDialogSureCancel rxDialogEditSureCancel = new RxDialogSureCancel(mContext);
        rxDialogEditSureCancel.getLogoView().setVisibility(View.GONE);
        rxDialogEditSureCancel.getTitleView().setTextSize(18);
        rxDialogEditSureCancel.getTitleView().setTextColor(Color.BLACK);
        rxDialogEditSureCancel.setTitle("提示");
        rxDialogEditSureCancel.setContent("通知栏权限没有开启，请前去开启！");
        rxDialogEditSureCancel.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogEditSureCancel.dismiss();
                if (mOnNextLitener != null) {
                    mOnNextLitener.onNext(0);
                }
            }
        });
        rxDialogEditSureCancel.setSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogEditSureCancel.dismiss();
                gotoSet(mContext);
                if (mOnNextLitener != null) {
                    mOnNextLitener.onNext(0);
                }
            }
        });
        rxDialogEditSureCancel.show();
    }

    private NotificationManager notificationManager;
    private Context mContext;

    private Notification notification;
    public static final int NOTIFICATION_ID = 10003;


    public NotificationUtil(Context mContext) {
        this.mContext = mContext;
        notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    }

    /**
     * 展示通知栏
     */
    public void showNotification(String title,String content,String infoType,String type,String infoId) {
        String id = "channel_demo";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(id, mContext.getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW);
            mChannel.setDescription("通知栏");
            mChannel.enableLights(false);
            mChannel.setLightColor(Color.BLUE);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

            RemoteViews mRemoteViews = new RemoteViews(mContext.getPackageName(), R.layout.view_notify_big);

            notificationManager.createNotificationChannel(mChannel);
            notification = new NotificationCompat.Builder(mContext, id)
                    .setSmallIcon(R.mipmap.gyss_logo_new)
                    .setWhen(System.currentTimeMillis())
                    .setContentIntent(getDefaultIntent(infoId,title,type,infoType,PendingIntent.FLAG_UPDATE_CURRENT))
                    .setCustomBigContentView(getContentView(title,content,true))
                    .setCustomContentView(getContentView(title,content,false))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setTicker(title)
                    .setOngoing(true)
                    .setAutoCancel(true)
                    .setChannelId(mChannel.getId())
                    .build();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification = new NotificationCompat.Builder(mContext, id)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.gyss_logo_new)
                    .setContentIntent(getDefaultIntent(infoId,title,type,infoType,PendingIntent.FLAG_UPDATE_CURRENT))
                    .setCustomBigContentView(getContentView(title,content,true))
                    .setCustomContentView(getContentView(title,content,false))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setTicker(title)
                    .setOngoing(true)
                    .setAutoCancel(true)
                    .build();
        } else {
            notification = new NotificationCompat.Builder(mContext, id)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.gyss_logo_new)
                    .setContentIntent(getDefaultIntent(infoId,title,type,infoType,PendingIntent.FLAG_UPDATE_CURRENT))
                    .setContent(getContentView(title,content,false))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setTicker(title)
                    .setOngoing(true)
                    .setAutoCancel(true)
                    .build();
        }
        notificationManager.notify(new Long(System.currentTimeMillis()).intValue(), notification);
    }

    private PendingIntent getDefaultIntent(String infoId,String title,String type,String infoType,int flags) {
        LoginBean user = new Gson().fromJson(SharedHelper.readValueByKeyForString(APP.getInstance().getApplicationContext(),"Member"),LoginBean.class);
        if("15".equals(infoType)){
            //通知公告
            Intent intent = new Intent(mContext,null);
            Bundle bundle = new Bundle();
            bundle.putString("path", BASE_WORK_URL+infoId+"&userId=");
            bundle.putString("title", "通知公告详情");
            bundle.putString("contentTitle", title);
            bundle.putString("collectType", "notice");
            bundle.putString("infoSign", "Notice");
            bundle.putString("fromActivity", "0");
            bundle.putString("id", infoId);
            intent.putExtras(bundle);
            return PendingIntent.getActivity(mContext, new Long(System.currentTimeMillis()).intValue(), intent, flags);
        }else if("typicalCase".equals(type)){
            //典型案例
            Intent intent = new Intent(mContext,null);
            Bundle bundle = new Bundle();
            bundle.putString("path", BASE_WORK_URL+infoId+"&userId=");
            bundle.putString("title", "典型案例详情");
            bundle.putString("contentTitle", title);
            bundle.putString("collectType", "knowledgeLib");
            bundle.putString("infoSign", "typicalCase");
            bundle.putString("fromActivity", "0");
            bundle.putString("id", infoId);
            intent.putExtras(bundle);
            return PendingIntent.getActivity(mContext, new Long(System.currentTimeMillis()).intValue(), intent, flags);
        }else if("11".equals(infoType)){
            //政策发布
            Intent intent = new Intent(mContext,null);
            Bundle bundle = new Bundle();
            bundle.putString("path", BASE_WORK_URL+infoId+"&userId=");
            bundle.putString("title", "政策发布详情");
            bundle.putString("contentTitle", title);
            bundle.putString("collectType", "notice");
            bundle.putString("infoSign", "PolicyIssued");
            bundle.putString("fromActivity", "0");
            bundle.putString("id", infoId);
            intent.putExtras(bundle);
            return PendingIntent.getActivity(mContext, new Long(System.currentTimeMillis()).intValue(), intent, flags);
        }else{
            //指定管辖
            Intent intent = null;
            Bundle bundle = new Bundle();
            bundle.putString("id",infoId+"");
            bundle.putInt("fromType",1);
            if("0".equals(infoType)){
                bundle.putString("caseType","CasePenalty");
                intent = new Intent(mContext,null);
            }else if("5".equals(infoType)){
                bundle.putString("caseType","CrimeCase");
                intent = new Intent(mContext, null);
            }else if("4".equals(infoType)){
                bundle.putString("caseType","CaseJudgment");
                intent = new Intent(mContext, null);
            }else if("8".equals(infoType)){
                bundle.putString("caseType","EnvironmentSupervise");
                intent = new Intent(mContext, null);
            }else if("1".equals(infoType)){
                bundle.putString("caseType","PublicOpinion");
                intent = new Intent(mContext, null);
            }else if("6".equals(infoType)){
                bundle.putString("caseType","LeaderHotline");
                intent = new Intent(mContext, null);
            } else if("3".equals(infoType)){
                bundle.putString("caseType","ComplaintsReport");
                intent = new Intent(mContext, null);
            }
            intent.putExtras(bundle);
            return PendingIntent.getActivity(mContext, new Long(System.currentTimeMillis()).intValue(),intent, flags);
        }
    }

    /**
     * 获取自定义通知栏view
     *
     * @param showBigView
     * @return
     */
    private RemoteViews getContentView(String title,String content,boolean showBigView) {
        RemoteViews mRemoteViews = new RemoteViews(mContext.getPackageName(), R.layout.view_notify_big);
        mRemoteViews.setTextViewText(R.id.title, title);
        mRemoteViews.setTextViewText(R.id.content, content);
        return mRemoteViews;
    }

    /**
     * 之前发布通知的取消  (所有当前 应用所发布的通知)
     */
    public void cancelAll() {
        notificationManager.cancelAll();
    }
}
